#coding=utf-8
from uliweb import expose,json, functions

#可以省略直接引用
from uliweb import request, error

import datetime
import os
from sqlalchemy import or_

def __begin__():
    """
    用户验证 权限验证
    """
    from uliweb import functions
    functions.require_login()
    return functions.has_role()

@expose('/myuser')
class User(object):

    def __init__(self):
        from uliweb.orm import get_model
        self.usermodel = get_model('user')
        self.notifymodel = get_model('notify')
        self.usergroupmodel = get_model('usergroup')
        #self.menurolemodel = get_model('menurole')

    
    def user(self):
        return {}

    def useradd(self):
        return {}
    
    def useredit(self):
        """
        编辑用户
        """
        _id = request.GET.get("id")
        
        ormdata = list(self.usermodel.filter(self.usermodel.c.id == int(_id)).limit(1))[0]

        return {"ormdata":ormdata}

   
    def userdel(self):
        """
        删除用户,支持批量和单一删除
        """
        if request.method == 'GET':
            error("你访问的页面不存在！请联系管理员")
            
        _id = request.POST.get('id')

        user = request.user
        
        mid = []
        for i in _id.split(','):
            #自己不能被删除
            if int(i) != user.id:
                mid.append(int(i))       
            
        try:
            self.usermodel.filter(self.usermodel.c.id.in_(mid)).remove()

            d = {"status":200,"msg":"删除用户成功"}
        except:
            d = {"status":500,"msg":"删除用户失败"}
            
        return json(d)
    
    def usersave(self):
        """
        保存修改用户
        """
        if request.method == 'GET':
            return json({"status":500,"msg":"非法访问"})

        _id = request.POST.get('id')
        
        username = request.POST.get('username')
        password = request.POST.get('password')
        nickname = request.POST.get('nickname')
        mobile = request.POST.get('mobile')
        email = request.POST.get('email')
        is_superuser = request.POST.get('is_superuser')

            
        if _id == None:
            ormdata = self.usermodel(username=username,
                                      nickname=nickname,
                                      mobile=mobile,
                                      email=email,
                                      #密码使用sha1加密
                                      password=functions.encrypt_password(password),
                                      is_superuser = int(is_superuser)
                                      )
        else:
            ormdata = functions.get_object(self.usermodel, _id, cache=True, use_local=True)
            ormdata.username = username
            ormdata.nickname=nickname
            ormdata.mobile=mobile
            ormdata.email=email
            ormdata.is_superuser=int(is_superuser)
        
        try:
            ormdata.save()
            
            return json({"status":200,"msg":"保存成功"})
        except:
            return json({"status":500,"msg":"用户已经存在"})
    
    def userprofile(self):
        """
        用户个人资料
        """
        user = request.user
        
        if user.is_superuser:
            #管理员显示自己的和注册类型的
            key = or_(self.notifymodel.c.notify_type == 1,
                      self.notifymodel.c.receiveuser_id == user.id)
    
            #防止发送用户被删或者不存在
            #select * from notify where notify.senduser_id in (select id from user)
            ormdata = self.notifymodel.filter(key).filter(self.notifymodel.c.senduser_id.in_(self.usermodel.filter().fields('id')))
    
        else:
            #非管理员显示自己相关的
            ormdata = self.notifymodel.filter(self.notifymodel.c.receiveuser_id == user.id).filter(self.notifymodel.c.senduser_id.in_(self.usermodel.filter().fields('id')))
            
        return {"ormdata":ormdata}

    def userprofileedit(self):
        """
        用户个人资料编辑
        """
        user = request.user
    
        ormdata = list(self.usermodel.filter(self.usermodel.c.id == user.id ).limit(1))[0]
    
        return {"ormdata":ormdata}   
    
    def userprofilesave(self):
        """
        保存个人修改信息
        """
        if request.method == 'GET':
            return json({"status":500,"msg":"非法访问"})

        _id = request.POST.get('id')

        username = request.POST.get('username')
        nickname = request.POST.get('nickname')
        mobile = request.POST.get('mobile')
        email = request.POST.get('email')

        user = request.user
        
        if user.id != int(_id):
            return json({"status":500,"msg":"非法访问"})
        

        ormdata = functions.get_object(self.usermodel, user.id, cache=True, use_local=True)
        ormdata.username = username
        ormdata.nickname=nickname
        ormdata.mobile=mobile
        ormdata.email=email

        try:
            ormdata.save()

            return json({"status":200,"msg":"保存成功"})
        except:
            return json({"status":500,"msg":"用户已经存在"})    
    
    def userprofilepassword(self):
        """
        用户个人密码修改
        """
        return {}
    
    
    def checkpassword(self):
        """
        检查用户修改个人密码时候的密码检查
        """
        oldpassword = request.POST.get("oldpassword")
        
        user = request.user
        
        result = functions.check_password(oldpassword.strip(),user.password)
        
        #用于jquery validate remote
        if not result:
            return "false"
        else:
            return "true"
        
        
    def userchangepassword(self):
        """
        个人修改个人用户密码
        """
        user = request.user
        
        if request.method == 'GET':
            error("你访问的页面不存在！请联系管理员")

        elif request.method == 'POST':
            
            password = request.POST.get('password')
            
            ormdata = functions.get_object(self.usermodel, user.id, cache=True, use_local=True)
            ormdata.password = functions.encrypt_password(password.strip())
            
            try:
                ormdata.save()
                return json({"status":200,"msg":"密码修改成功"})
            except:
                return json({"status":500,"msg":"密码修改失败"})


    def avatarupload(self):
        """
        头像上传
        """
        from common import image
        import simplejson
        
        if request.method == 'GET':
            error("你访问的页面不存在！请联系管理员")
            
        user = request.user
        ormdata = functions.get_object(self.usermodel, user.id, cache=True, use_local=True)
            
        #头像大小{"x":251.3618030050083,"y":57.48617696160264,"height":495.44,"width":495.44,"rotate":0}
        avatar_data = request.POST.get("avatar_data")
        filename = request.files['avatar_file'].filename
        file_obj = request.files['avatar_file'].stream
        
        #得到今天日期，格式化为20160405
        today = datetime.datetime.today().strftime("%Y%m%d")
        #保存路径
        subpath = os.path.join("avatar",today)
        new_image = image.avatar_image(file_obj,simplejson.loads(avatar_data))
        new_filename = functions.save_file(filename,new_image,subpath = subpath)
        
        #对文件进行替换 ./uploads\avatar\20160405\cbc296b5c6fdc6d2625fbed4d96b26cf.jpg
        file_url = os.path.join(settings.UPLOAD["TO_PATH"],subpath,new_filename).replace('\\', '/').replace('./', '/')
        
        #保存小头像
        new_small_image = image.resize_image(new_image,size=(64, 64))
        new_small_filename = functions.save_file(new_filename.replace('.','_small.'),new_small_image,convert=False,subpath = subpath)
        
        file_small_url = os.path.join(settings.UPLOAD["TO_PATH"],subpath,new_filename.replace('.','_small.')).replace('\\', '/').replace('./', '/')
        
        #保存url进数据库
        ormdata.image = file_url
        ormdata.image_small = file_small_url
        
        try:
            ormdata.save()
            return json({"status":200,"msg":"头像更新成功",'url':file_url})
        except:
            return json({"status":500,"msg":"头像更新失败"})
        
    def userunlocklogin(self):
        """
        恢复用户登录状态
        """
        if request.method == 'GET':
            error("你访问的页面不存在！请联系管理员")
            
        _id = request.POST.get('id')
        
        mid = []
        for i in _id.split(','):
            mid.append(int(i))
        
        try:
            self.usermodel.filter(self.usermodel.c.id.in_(mid)).update(locked=0)
    
            d = {"status":200,"msg":"恢复用户登录成功"}
        except:
            d = {"status":500,"msg":"恢复用户登录失败"}
        return json(d)    

    def userlocklogin(self):
        """
        锁定用户登录状态
        """
        if request.method == 'GET':
            error("你访问的页面不存在！请联系管理员")        
        
        _id = request.POST.get('id')
        
        mid = []
        for i in _id.split(','):
            mid.append(int(i))
        
        try:
            self.usermodel.filter(self.usermodel.c.id.in_(mid)).update(locked=1)
            
            d = {"status":200,"msg":"锁定用户登录成功"}
        except:
            d = {"status":500,"msg":"锁定用户登录失败"}
        return json(d)   
    
    def userlockregister(self):
        """
        显示注册用户并且锁定的用户
        """
        return {}
    
    
    def usergroup(self):
        """
        用户组管理页面
        """
        return {}

    def usergroupadd(self):
        """
        添加用户组
        """
        data = []
        
        #列出非管理员用户的非锁定账户
        ormdata = self.usermodel.filter(self.usermodel.c.is_superuser == 0).filter(self.usermodel.c.locked == 0).filter().fields('id','nickname')
        
        for i in ormdata:
            select_data =  '<option value="' + str(i.id) + '">' + i.nickname + '</option>'
            data.append(select_data)
            
        return {"html_user":"".join(data)}

    def usergroupedit(self):
        """
        编辑用户
        """
        _id = request.GET.get("id")

        ormdata_usergroup = functions.get_object(self.usergroupmodel, _id, cache=True, use_local=True)

        users = ormdata_usergroup.users.ids()
        data = []
        
        #列出非管理员用户的非锁定账户
        ormdata = self.usermodel.filter(self.usermodel.c.is_superuser == 0).filter(self.usermodel.c.locked == 0).filter().fields('id','nickname')
    
        for i in ormdata:
            if i.id in users:
                select_data =  '<option value="' + str(i.id) + '" selected>' + i.nickname + '</option>'
            else:
                select_data =  '<option value="' + str(i.id) + '">' + i.nickname + '</option>'
                
            data.append(select_data)        
        
        return {"ormdata":ormdata_usergroup,"html_user":"".join(data)}


    def usergroupdel(self):
        """
        删除用户组,支持批量和单一删除
        """
        if request.method == 'GET':
            error("你访问的页面不存在！请联系管理员")

        _id = request.POST.get('id')

        mid = []
        for i in _id.split(','):
            
            ormdata = functions.get_object(self.usergroupmodel, int(i), cache=True, use_local=True)

            #先删除关联的用户
            ormdata.users.remove(ormdata.users.ids())
            
            #删除记录
            ormdata.delete()
    
        d = {"status":200,"msg":"删除成功"}

        return json(d)

    def usergroupsave(self):
        """
        保存修改用户组
        """
        if request.method == 'GET':
            return json({"status":500,"msg":"非法访问"})

        _id = request.POST.get('id')

        name = request.POST.get('name')
        users = request.POST.getlist('users')
        
        #用于标识是新增还是修改.默认新增True
        flag=True

        if _id == None:
            ormdata = self.usergroupmodel(name=name)
        else:
            flag = False
            ormdata = functions.get_object(self.usergroupmodel, _id, cache=True, use_local=True)
            ormdata.name = name

        
        Begin()
        try:
            ormdata.save()
        
            #多对多操作
            ormdata_user = list(self.usermodel.filter(self.usermodel.c.id.in_(users)).filter().fields('id'))
        
            if flag:
                ormdata.users.add(ormdata_user)
            else:
                ormdata.users.update(ormdata_user)

            Commit()
            return json({"status":200,"msg":"保存成功"})
        except:
            Rollback()
            return json({"status":500,"msg":"用户组已经存在"})